# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.user_permission_api_service import UserPermissionApiService
from typing import List


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class UserPermissionApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def list_user_permissions(self, db: Session = Depends(get_db), name: str = Query(None),
                                    page: int = Query(default=1, ge=1), limit: int = Query(default=20, ge=1)):
        """
        权限列表
        """
        service = UserPermissionApiService(db)
        result = await service.list_user_permissions(page, limit, name)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def create_user_permission(self, data: dict, db: Session = Depends(get_db)):
        """
        添加权限
        """
        service = UserPermissionApiService(db)
        result = await service.create_user_permission(data)
        return self.success_response(data=result, message="角色添加成功")

    async def update_user_permission(self, pid: int, data: dict, db: Session = Depends(get_db)):
        """
        编辑权限
        """
        service = UserPermissionApiService(db)
        result = await service.update_user_permission(data, pid)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="更新成功")

    async def delete_user_permission(self, pid: str, db: Session = Depends(get_db)):
        """
        删除权限
        """
        service = UserPermissionApiService(db)
        result = await service.delete_user_permission(pid)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="删除成功")

    async def get_user_permission(self, db: Session = Depends(get_db)):
        """
        获取权限
        """

    async def detail_user_permission(self, pid: int, db: Session = Depends(get_db)):
        """
        权限详情
        """
        service = UserPermissionApiService(db)
        result = await service.detail_user_permission(pid)
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")

    async def update_permission_menu(self, data: dict, db: Session = Depends(get_db)):
        """
        更新权限菜单
        json "permission_ids": [1, 2, 3]
        """
        # 查找菜单是否存在
        service = UserPermissionApiService(db)
        result = await service.update_permission_menu(data['menuId'], data['permissionIds'])
        if isinstance(result, dict) and "error" in result:
            return self.failure_response(status_code=400, message=result["error"])
        return self.success_response(data=result, message="success")



# 使用
user_permission_api = UserPermissionApi()
router = user_permission_api.router
